using System.Collections.Generic;
using UnityEditor;
using UnityEngine;

namespace Net.AI
{
    public class Agent : MonoBehaviour
    {
        public float speed = 5f;
        private List<Vector3> pathPoints = new List<Vector3>();

        public int Type;

        // Start is called before the first frame update
        void Start()
        {

        }

        // Update is called once per frame
        void Update()
        {
            if (pathPoints.Count > 0)
            {
                int index = pathPoints.Count - 1;
                var targetPos = pathPoints[index];
                targetPos.y = transform.position.y; //保持目标和物体在同一高度
                transform.LookAt(targetPos);
                transform.position = Vector3.MoveTowards(transform.position, targetPos, speed * Time.deltaTime);
                if (Vector3.Distance(transform.position, targetPos) < 0.1f)
                {
                    pathPoints.RemoveAt(index);
                }
            }
        }

        public bool SetDestination(Vector3 target)
        {
            switch (Type)
            {
                case 0:
                    Pathfinding.I.GetPath(transform.position, target, pathPoints);
                    break;
                case 1:
                    RecastSystem.I.GetPath(transform.position, target, pathPoints);
                    break;
                case 2:
                    NavmeshSystemUnity.I.GetPath(transform.position, target, pathPoints);
                    break;
            }
            pathPoints.Reverse(); //反转是因为后面每一步会进行移除, 移除时数组不会进行倒塌操作
            return pathPoints.Count > 0;
        }

        void OnDrawGizmos()
        {
            if (pathPoints.Count > 0)
            {
                int index = pathPoints.Count - 1;
                Handles.DrawLine(transform.position, pathPoints[index]);
                for (int i = index; i > 0; i--)
                {
                    Handles.DrawLine(pathPoints[i], pathPoints[i - 1]);
                }
            }
        }
    }
}